package org.example.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    public static final String WEBSOCKET_EXCHANGE = "websocket.exchange";
    public static final String WEBSOCKET_QUEUE_PREFIX = "websocket.queue.";
    public static final String WEBSOCKET_ROUTING_KEY_PREFIX = "websocket.routing.";

    @Value("${spring.application.name}")
    private String serverId;

    @Bean
    public TopicExchange websocketExchange() {
        return new TopicExchange(WEBSOCKET_EXCHANGE);
    }

    @Bean
    public Queue websocketQueue() {
        return new Queue(WEBSOCKET_QUEUE_PREFIX + serverId, true);
    }

    @Bean
    public Binding websocketBinding(TopicExchange websocketExchange, Queue websocketQueue) {
        return BindingBuilder.bind(websocketQueue)
                .to(websocketExchange)
                .with(WEBSOCKET_ROUTING_KEY_PREFIX + serverId + ".#");
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(jackson2JsonMessageConverter());
        return template;
    }

    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}